package sub

import (
	"context"
	"fmt"
	"os"

	"quipus/internal/server/version"
	"quipus/internal/utils"

	"github.com/spf13/cobra"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

const (
	CfgFileTypeIni = iota
	CfgFileTypeCmd
)

type CliCfg struct {
	QPAddress string `yaml:"qpaddr"`
	Username  string `yaml:"username"`
	Password  string `yaml:"password"`
	Token     string `yaml:"token"`
	WS        string `yaml:"ws"`
}

var (
	cfgFile     string
	showVersion bool

	QpConfig CliCfg
)

func (cfg *CliCfg) UnaryClientInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
	// respMetadata := metadata.MD{}
	// ctxWithMeta := metadata.NewOutgoingContext(ctx, respMetadata)
	var headerMD metadata.MD

	// 添加 grpc.Header 到 opts 中，用于接收响应头
	opts = append(opts, grpc.Header(&headerMD))

	err := invoker(ctx, method, req, reply, cc, opts...)
	if err != nil {
		return err
	}
	if tokens := headerMD.Get("Authorization"); len(tokens) > 0 {
		cfg.Token = tokens[0]
	}
	return nil
}

func init() {
	e := utils.ReadYamlConfig("./etc/cli/qp.yaml", &QpConfig)
	if e != nil {
		fmt.Println("load cfg err: ", e.Error())
		return
	}
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "./etc/cli/qp.yaml", "config file of qp")
	rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of qp")
	rootCmd.CompletionOptions.DisableDefaultCmd = true
}

func RegisterCommonFlags(cmd *cobra.Command) {

}

func AddCommand(cmd *cobra.Command) {
	rootCmd.AddCommand(cmd)
}

var rootCmd = &cobra.Command{
	Use:   "qpc",
	Short: "qpc is the client of quipus (https://github.com/quipus/quipus)",
	RunE: func(cmd *cobra.Command, args []string) error {
		if showVersion {
			fmt.Println(version.Version)
			return nil
		}

		return nil
	},
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		os.Exit(1)
	}
}
